package com.android.dialer.extendboard;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;

import com.google.gson.Gson;

public class PickContact extends AppCompatActivity {
    private static final int CONTACT_PICK_REQUEST = 1;
    private SpeedDialItem currentItem;
    private int keyFromIntent;
    private final String TAG = "PickContact";

    private EditText nameEditText;
    private EditText numberEditText;
    private Button fromContactButton;
    private Button saveButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pick_contact);

        // Initialize views
        Toolbar toolbar = findViewById(R.id.toolbar);
        nameEditText = findViewById(R.id.nameEditText);
        numberEditText = findViewById(R.id.numberEditText);
        fromContactButton = findViewById(R.id.fromContactButton);
        saveButton = findViewById(R.id.saveButton);

        // Set up Toolbar
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        keyFromIntent = getIntent().getIntExtra("key", -1);
        if (keyFromIntent == -1) {
            Toast.makeText(this, "Invalid key", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        ContentResolver contentResolver = getContentResolver();
        String[] args = {String.valueOf(keyFromIntent)};
        Cursor cursor = contentResolver.query(PhonesContentProvider.CONTENT_URI, null, "", args, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                String value = cursor.getString(cursor.getColumnIndex(PhonesContentProvider.COLUMN_VALUE));
                currentItem = new Gson().fromJson(value, SpeedDialItem.class);
            } else {
                currentItem = new SpeedDialItem();
                currentItem.setId(keyFromIntent);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        Log.d(TAG, "onCreate: " + keyFromIntent);

        if (currentItem.isActive()) {
            nameEditText.setText(currentItem.getName());
            numberEditText.setText(currentItem.getNumber());
        } else {
            nameEditText.setText("");
            numberEditText.setText("");
        }

        fromContactButton.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                    != PermissionChecker.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_CONTACTS},
                        CONTACT_PICK_REQUEST);
            } else {
                pickContact();
            }
        });

        saveButton.setOnClickListener(v -> saveData());
    }

    private void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(intent, CONTACT_PICK_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CONTACT_PICK_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri contactUri = data.getData();
            String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone.PHOTO_URI};
            try (Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    currentItem.setName(name);
                    currentItem.setNumber(number);
                    String avatar = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                    currentItem.setAvatar(avatar != null ? avatar : "");
                    nameEditText.setText(name);
                    numberEditText.setText(number);
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // Handle the back button click
            setResult(RESULT_CANCELED);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CONTACT_PICK_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PermissionChecker.PERMISSION_GRANTED) {
                pickContact();
            } else {
                Toast.makeText(this, "Permission denied to access contacts", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void saveData() {
        String name = nameEditText.getText().toString();
        String number = numberEditText.getText().toString();
        if (name.isEmpty() || number.isEmpty()) {
            Toast.makeText(this, "Please fill both name and number", Toast.LENGTH_SHORT).show();
            return;
        }

        currentItem.setName(name);
        currentItem.setNumber(number);
        currentItem.setActive(true);
        saveDataToSharedPreferences(currentItem);

        Log.d(TAG, "saveData: " + currentItem);
        Intent resultIntent = new Intent();
        resultIntent.putExtra("item", currentItem);
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    private void saveDataToSharedPreferences(SpeedDialItem item) {
        ContentResolver contentResolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(PhonesContentProvider.COLUMN_KEY, String.valueOf(item.getId()));
        values.put(PhonesContentProvider.COLUMN_VALUE, new Gson().toJson(item));
        int ret = contentResolver.update(PhonesContentProvider.CONTENT_URI, values, null, null);
        Log.d(TAG, "saveDataToSharedPreferences: ret: " + ret);
    }
}